package com.weiyi.mashangzhu.Roomer.Activity;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hyphenate.chat.EMClient;
import com.squareup.okhttp.Request;
import com.weiyi.mashangzhu.API.API;
import com.weiyi.mashangzhu.Application.MyApp;
import com.weiyi.mashangzhu.Base.BaseActivity;
import com.weiyi.mashangzhu.R;
import com.weiyi.mashangzhu.Utils.FileUtil;
import com.weiyi.mashangzhu.Utils.GlideImgManager;
import com.weiyi.mashangzhu.Utils.LoadingDialog;
import com.weiyi.mashangzhu.Utils.NetUtil;
import com.weiyi.mashangzhu.Utils.SPUtils;
import com.weiyi.mashangzhu.Utils.T;
import com.weiyi.mashangzhu.Utils.UiUtil;
import com.weiyi.mashangzhu.easemob.DemoHelper;
import com.weiyi.mashangzhu.easemob.db.ChatDao;
import com.weiyi.mashangzhu.listener.CallBackListener;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class PersonInfoActivity extends BaseActivity {


    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.person_info_head_img)
    ImageView personInfoHeadImg;
    @BindView(R.id.person_info_head)
    RelativeLayout personInfoHead;
    @BindView(R.id.person_info_user_name)
    TextView personInfoUserName;
    @BindView(R.id.person_info_user)
    RelativeLayout personInfoUser;
    @BindView(R.id.person_info_phone_number)
    TextView personInfoPhoneNumber;
    @BindView(R.id.person_info_phone)
    RelativeLayout personInfoPhone;
    @BindView(R.id.person_info_update)
    RelativeLayout personInfoUpdate;
    @BindView(R.id.person_info_exit)
    Button personInfoExit;
    JSONObject jsonObject1 = null;
    TextView pop_friend_wx, pop_friend_wxc, pop_off;
    private static final int REQUESTCODE_PICK = 0;        // 相册选图标记
    private static final int REQUESTCODE_TAKE = 1;        // 相机拍照标记
    private static final int REQUESTCODE_CUTTING = 2;    // 图片裁切标记
    private static final String IMAGE_FILE_NAME = "avatarImage.jpg";// 个人文件名称
    private String urlpath;            // 图片本地路径
    private String resultStr = "";    // 服务端返回结果集
    PopupWindow popupWindow;
    private Uri imageUri;//相机拍照图片保存地址
    private Uri outputUri;//裁剪万照片保存地址
    private Uri uritempFile;
    File file = null;
    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == 1) {
                try {
                    GlideImgManager.glideLoader(PersonInfoActivity.this, API.BaseApi_url + jsonObject1.getString("uHead"), R.mipmap.logo, personInfoHeadImg, 0);
                    personInfoUserName.setText(jsonObject1.getString("uNickname") + "");
                    personInfoPhoneNumber.setText((jsonObject1.getString("uAccount") + "").substring(0, 3) + "****" + (jsonObject1.getString("uAccount") + "").substring(7));
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            } else if (msg.what == 0) {
                initView();
            }
            return false;
        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_person_info);
        ButterKnife.bind(this);
        initView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        initView();
    }

    @Override
    public void initView() {
        super.initView();
        OkHttpUtils.get().addParams("token", SPUtils.get(this, "token", "") + "").url(API.BaseApi_R + API.PersonInfo_Api_R).build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Request request, Exception e) {
                        T.showShort(PersonInfoActivity.this, "网络连接失败，请检查一下网络设置");
                    }

                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            jsonObject1 = jsonObject.getJSONObject("data");
                            int status = jsonObject.getInt("status");
                            Log.e("ffffff", "status=" + status);
                            Log.e("ffffff", "status=" + response);
                            Log.e("ffffff", "status=" + jsonObject1.getString("uAccount"));
//                            if (status==0){
                            handler.sendEmptyMessage(1);
                            String head = jsonObject1.getString("data");


//                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }


                    }
                });

    }

    public void showPopupWindow() {
        View contentView = LayoutInflater.from(this).inflate(R.layout.layout_dialog_pic, null);
        popupWindow = new PopupWindow(contentView,
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);
        pop_friend_wx = (TextView) contentView.findViewById(R.id.pop_friend_wx);
        pop_friend_wxc = (TextView) contentView.findViewById(R.id.pop_friend_wxc);
        pop_off = (TextView) contentView.findViewById(R.id.pop_off);
        pop_off.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        pop_friend_wx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    requestPermission(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0x001);
                } else {
                    Intent takeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    //下面这句指定调用相机拍照后的照片存储的路径
                    File file = new File(Environment.getExternalStorageDirectory(), IMAGE_FILE_NAME);
                    Uri f = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), IMAGE_FILE_NAME));
                    if (Build.VERSION.SDK_INT < 24) {
                        takeIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                                Uri.fromFile(file));
                    } else {
                        takeIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                                FileProvider.getUriForFile(PersonInfoActivity.this, "com.weiyi.mashangzhu.fileprovider", file));
                    }

                    startActivityForResult(takeIntent, REQUESTCODE_TAKE);
                }

            }
        });
        pop_friend_wxc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    requestPermission(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0x002);
                } else {
                    Intent pickIntent = new Intent(Intent.ACTION_PICK, null);
                    // 如果朋友们要限制上传到服务器的图片类型时可以直接写如："image/jpeg 、 image/png等的类型"
                    pickIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                    startActivityForResult(pickIntent, REQUESTCODE_PICK);
                }
            }
        });
        popupWindow.setTouchable(true);
        popupWindow.setAnimationStyle(R.style.popup_window_bottom_animation);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0x55000000));
        // 设置好参数之后再show
        if (popupWindow.isShowing()) {

        } else {
            popupWindow.showAsDropDown(contentView);
        }

    }

    @Override
    public void permissionSuccess(int requestCode) {
        super.permissionSuccess(requestCode);
        if (requestCode == 0x001) {
            Intent takeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            //下面这句指定调用相机拍照后的照片存储的路径
            File file = new File(Environment.getExternalStorageDirectory(), IMAGE_FILE_NAME);
            Uri f = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), IMAGE_FILE_NAME));
            if (Build.VERSION.SDK_INT < 24) {
                takeIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                        Uri.fromFile(file));
            } else {
                takeIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                        FileProvider.getUriForFile(PersonInfoActivity.this, "com.weiyi.mashangzhu.fileprovider", file));
            }

            startActivityForResult(takeIntent, REQUESTCODE_TAKE);
        } else if (requestCode == 0x002) {
            Intent pickIntent = new Intent(Intent.ACTION_PICK, null);
            // 如果朋友们要限制上传到服务器的图片类型时可以直接写如："image/jpeg 、 image/png等的类型"
            pickIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
            startActivityForResult(pickIntent, REQUESTCODE_PICK);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUESTCODE_PICK:// 直接从相册获取
                try {
                    Log.e("vvvvvvvvvvvvvvvvv", "剪裁前");
                    startPhotoZoom(data.getData());

                } catch (NullPointerException e) {
                    e.printStackTrace();// 用户点击取消操作
                }
                break;
            case REQUESTCODE_TAKE:// 调用相机拍照
                File temp = new File(Environment.getExternalStorageDirectory() + "/" + IMAGE_FILE_NAME);
                if (Build.VERSION.SDK_INT < 24) {
                    imageUri = Uri.fromFile(temp);
                } else {
                    //Android 7.0系统开始 使用本地真实的Uri路径不安全,使用FileProvider封装共享Uri
                    //参数二:fileprovider绝对路径 com.dyb.testcamerademo：项目包名
                    imageUri = FileProvider.getUriForFile(PersonInfoActivity.this, "com.weiyi.mashangzhu.fileprovider", temp);
                }
                startPhotoZoom(imageUri);
                break;
            case REQUESTCODE_CUTTING:// 取得裁剪后的图片
                Log.e("vvvvvvvvvvvvvvvvv", "剪裁后");
                if (data != null) {
                    //将Uri图片转换为Bitmap
                    try {
                        Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uritempFile));
                        if (bitmap != null) {
                            Log.e("bbbbbbbbbbbb", "!=null");
                            setPicToView(bitmap);
                        } else {
                            Log.e("bbbbbbbbbbbb", "=null");
                        }
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }

                } else {
                    Log.e("vvvvvvvvvvvvvvvvv", "data=null");
                }
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 裁剪图片方法实现
     *
     * @param uri
     */
    public void startPhotoZoom(Uri uri) {
        Log.e("vvvvvvvvvvvvvvvvv", "剪裁");
        // 创建File对象，用于存储裁剪后的图片，避免更改原图
        file = new File(getExternalCacheDir(), "crop_image.jpg");
        try {
            if (file.exists()) {
                file.delete();
            }
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Intent intent = new Intent("com.android.camera.action.CROP");
        uritempFile = Uri.fromFile(file);
        if (Build.VERSION.SDK_INT < 24) {
        } else {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        intent.setDataAndType(uri, "image/*");
        // crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
        intent.putExtra("return-data", true);
        //uritempFile为Uri类变量，实例化uritempFile

        intent.putExtra(MediaStore.EXTRA_OUTPUT, uritempFile);
//       intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
//        intent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri);
        startActivityForResult(intent, REQUESTCODE_CUTTING);
    }

    /**
     * 保存并上传裁剪之后的图片数据
     */
    private void setPicToView(Bitmap bitmap) {
        LoadingDialog.show(this);
        urlpath = FileUtil.saveFile(PersonInfoActivity.this, "crop_image.jpg", bitmap);
        Log.e("vvvvvvvvvvvvvvvvv", "save=" + urlpath);
        popupWindow.dismiss();
        new Thread(uploadImageRunnable).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(500);
                    LoadingDialog.dismiss(PersonInfoActivity.this);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 使用HttpUrlConnection模拟post表单进行文件
     * 上传平时很少使用，比较麻烦
     * 原理是： 分析文件上传的数据格式，然后根据格式构造相应的发送给服务器的字符串。
     */
//    上传头像
    Runnable uploadImageRunnable = new Runnable() {
        @Override
        public void run() {

            if (TextUtils.isEmpty(API.BaseApi_R + API.ChangeHead)) {
                Toast.makeText(PersonInfoActivity.this, "还没有设置上传服务器的路径！", Toast.LENGTH_SHORT).show();
                return;
            }

            Map<String, String> textParams = new HashMap<String, String>();
            Map<String, File> fileparams = new HashMap<String, File>();

            try {
                // 创建一个URL对象
                URL url = new URL(API.BaseApi_R + API.ChangeHead);
                textParams = new HashMap<String, String>();
                fileparams = new HashMap<String, File>();
                // 要上传的图片文件
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//                    file = new File(urlpath);
                    Log.e("vvvvvvvvvvvvvvvvv", "file");
                    fileparams.put("uHead", file);
                } else {
                    File file = new File(urlpath);
                    fileparams.put("uHead", file);
                }

                textParams.put("token", SPUtils.get(PersonInfoActivity.this, "token", "") + "");
                // 利用HttpURLConnection对象从网络中获取网页数据
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                // 设置连接超时（记得设置连接超时,如果网络不好,Android系统在超过默认时间会收回资源中断操作）
                conn.setConnectTimeout(5000);
                // 设置允许输出（发送POST请求必须设置允许输出）
                conn.setDoOutput(true);
                // 设置使用POST的方式发送
                conn.setRequestMethod("POST");
                // 设置不使用缓存（容易出现问题）
                conn.setUseCaches(false);
                conn.setRequestProperty("Charset", "UTF-8");//设置编码
                // 在开始用HttpURLConnection对象的setRequestProperty()设置,就是生成HTML文件头
                conn.setRequestProperty("ser-Agent", "Fiddler");
                // 设置contentType
                conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + NetUtil.BOUNDARY);
                OutputStream os = conn.getOutputStream();
                DataOutputStream ds = new DataOutputStream(os);
                NetUtil.writeStringParams(textParams, ds);
                NetUtil.writeFileParams(fileparams, ds);
                NetUtil.paramsEnd(ds);
                // 对文件流操作完,要记得及时关闭
                os.close();
                // 服务器返回的响应吗
                int code = conn.getResponseCode(); // 从Internet获取网页,发送请求,将网页以流的形式读回来
                // 对响应码进行判断
                if (code == 200) {// 返回的响应码200,是成功
                    // 得到网络返回的输入流
                    InputStream is = conn.getInputStream();
                    resultStr = NetUtil.readString(is);
                    uploadUserAvatar();
                } else {
                    Toast.makeText(PersonInfoActivity.this, "请求URL失败！", Toast.LENGTH_SHORT).show();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            handler.sendEmptyMessage(0);// 执行耗时的方法之后发送消给handler
        }
    };

    private void uploadUserAvatar() {
        String token = SPUtils.get(this, "token", "") + "";
        String[] split = token.split("@");
        if (split.length > 1) {
            String userAccount = split[1];
            if (userAccount != null) {
                findHead(userAccount);
            }
        }
    }

    private void findHead(final String id) {
        OkHttpUtils.get().addParams("id", id).url(API.BaseApi_R + API.findHeadandName).build().execute(new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {

            }

            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.getInt("status") == 0) {
                        JSONObject jsonObject1 = jsonObject.getJSONObject("data");
                        String uHead = jsonObject1.getString("uHead");
                        ChatDao chatDao = new ChatDao(PersonInfoActivity.this);
                        chatDao.update(id, "", uHead);
                    }
                } catch (JSONException e) {

                }
            }
        });
    }


    @OnClick({R.id.back, R.id.person_info_head, R.id.person_info_user, R.id.person_info_phone, R.id.person_info_update, R.id.person_info_exit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.person_info_head:
                showPopupWindow();
                break;
            case R.id.person_info_user:
                UiUtil.startActivity(this, ChangeNameActivity.class);
                break;
            case R.id.person_info_phone:
                UiUtil.startActivity(this, ChangePhoneActivity.class);
                break;
            case R.id.person_info_update:
                Intent intent = new Intent(this, PwdSetActivity.class);
                intent.putExtra("info", "roomer");
                startActivity(intent);
                break;
            case R.id.person_info_exit:
                LoadingDialog.show(PersonInfoActivity.this);
                OkHttpUtils.get()
                        .addParams("token", SPUtils.get(this, "token", "") + "")
                        .url(API.BaseApi_R + API.Quit)
                        .build()
                        .execute(new StringCallback() {
                            @Override
                            public void onError(Request request, Exception e) {
                                LoadingDialog.dismiss(PersonInfoActivity.this);
                                T.showShort(PersonInfoActivity.this, "数据加载失败，请稍后再试");
                            }

                            @Override
                            public void onResponse(String response) {
                                Log.e("uiiiiii", "re=" + response);
                                try {
                                    JSONObject jsonObject = new JSONObject(response);
                                    if (jsonObject.getInt("status") == 0) {
                                        logoutEaseMob();
                                    } else {
                                        LoadingDialog.dismiss(PersonInfoActivity.this);
                                        T.showShort(PersonInfoActivity.this, jsonObject.getString("msg"));
                                    }

                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }

                            }
                        });

                break;
        }
    }

    private void logoutEaseMob() {
        EMClient.getInstance().logout(true, new CallBackListener() {
            @Override
            public void onMainSuccess() {
                SPUtils.put(PersonInfoActivity.this, "token", "");
                SPUtils.put(PersonInfoActivity.this, "isLogin", "0");
                Intent intent = new Intent(PersonInfoActivity.this, LoginActivity.class);
                intent.putExtra("info", "logout");
                startActivity(intent);
//                UiUtil.startActivity(PersonInfoActivity.this,LoginActivity.class);

                LoadingDialog.dismiss(PersonInfoActivity.this);
            }

            @Override
            public void onMainError(int code, String message) {
                LoadingDialog.dismiss(PersonInfoActivity.this);
                T.showShort(PersonInfoActivity.this, "error:" + code + " " + message);
            }
        });
    }
}